package java8;

import java.util.HashMap;
import java.util.Map;

public class HashMapTest1 {
    public static void main(String[] args) {
        // computeIfAbsent key不存在的时候会put值,并返回值  key存在,就返会原值,不做put
        Map<String, String> map = new HashMap<>();
        map.put("a", "c");
        map.put("b", "h");
        map.put("c", "e");
        System.out.println(map.computeIfAbsent("a", k -> {
           return k + "1";
        })); // c
        System.out.println(map.computeIfAbsent("d", k -> {
            return k + "1";
        })); // d1
        System.out.println(map); // {a=c, b=h, c=e, d=d1}
        System.out.println();

        // compute始终会覆盖并返回新的value
        map.clear();
        map.put("a", "c");
        map.put("b", "h");
        map.put("c", "e");
        System.out.println(map.compute("a", (k, v) -> {
            return k + v;
        })); // ac
        System.out.println(map.compute("d", (k, v) -> {
            return k + v;
        })); // dnull
        System.out.println(map); // {a=ac, b=h, c=e, d=dnull}
        System.out.println();

        // computeIfPresent key存在的时候替换value,返回新value, key不存在就返回null,不put
        map.clear();
        map.put("a", "c");
        map.put("b", "h");
        map.put("c", "e");
        System.out.println(map.computeIfPresent("a", (k, v) -> {
            return k + v;
        })); // ac
        System.out.println(map.computeIfPresent("d", (k, v) -> {
            return k + v;
        })); // null
        System.out.println(map); // {a=ac, b=h, c=e}
        System.out.println();


        map.clear();
        map.put("a", "c");
        map.put("b", "h");
        map.put("c", "e");
        System.out.println(map.computeIfAbsent(null, k -> {
            return k + "1";
        })); // null1
        System.out.println(map); // {null=null1, a=c, b=h, c=e}
        System.out.println();

        map.clear();
        map.put("a", "c");
        map.put("b", "h");
        map.put("c", "e");
        System.out.println(map.compute(null, (k, v) -> {
            return k + v;
        })); // nullnull
        System.out.println(map); // {null=nullnull, a=c, b=h, c=e}
        System.out.println();
    }
}
